#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*cmp_fn)(void *v1, void *v2);
int int_cmp(void *v1, void *v2)
{
	return *(int *)v1 - *(int *)v2;
}
int quick_sort(void *array, int size, int len, cmp_fn cmp)
{
	if (len < 2) return;
	char pivot[size];
	int start = 0, si = 0, end = len, ei = len-1, i;
	memcpy(pivot, (char *)array+(len/2)*size, size);
	memcpy((char *)array+(len/2)*size, array, size);
	while (ei > si) {
		while(ei > si && cmp((char *)array+ei*size, pivot) > 0) ei--;
		if (ei > si) memcpy((char *)array+(si++*size), (char *)array+ei*size, size);
		while(ei > si && cmp((char *)array+si*size, pivot) < 0) si++;
		if (ei > si) memcpy((char *)array+(ei--*size), (char *)array+si*size, size);
	}
	memcpy((char *)array+ei*size, pivot, size);

	quick_sort((char *)array, size, ei, int_cmp);
	quick_sort((char *)array+(ei+1)*size, size, end - ei - 1, int_cmp);
	return 0;
}

void main(void)
{	
	int i;
	int a[7] = {3, 1, 7, 5, 4, 6, 2};
	//foo(5);
	quick_sort(a, sizeof(int), sizeof(a)/sizeof(a[0]), int_cmp);
	for (i = 0; i < 7; i++)
		printf("%d ", a[i]);
	printf("\n ");
}
